package TCP.OneToMore;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

class Message extends Thread
{
    private Socket socket;
    
    public Message (Socket socket)
    {
        this.socket = socket;
    }
    
    private void Message()
    {
        try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter printWriter = new PrintWriter(socket.getOutputStream())
        )
        {
            while(true)
            {
                printWriter.println(bufferedReader.readLine() + "[ok]");
                printWriter.flush();
            }
        }
        catch(IOException e)
        {
            System.out.println("客户端" + this.socket.getInetAddress() + "断开连接");
            e.printStackTrace();
        }
    }
    
    @Override
    public void run ()
    {
        this.Message();
    }
}

/**
 * 一对多应答型服务器
 */
public class EchoServer
{
    public static void main (String[] args)
    {
        try(ServerSocket serverSocket = new ServerSocket(9999))
        {
            while(true)
            {
                Socket socket = serverSocket.accept();
                new Message(socket).start();
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}
